<template>
	<view class="container">
		<u-navbar bgColor="#0e3a5e" title="工序详情" :autoBack="true" :placeholder="true" leftIconColor="#fff"
			:titleStyle="data.titleStyle">
		</u-navbar>
		<view class="pdBox">

			<block v-if="data.processDetails">
				<view class="activeStation" v-if="data.processDetails.name">
					<view class="name">工序：{{data.processDetails.name}}</view>
				</view>
				<view class="activeStation" v-if="data.processDetails.name" @click="openTree">
					<view class="name" style="display: flex; align-items: center;"><text>操作人：</text>
						<u--input placeholder="请选择操作人" disabled disabledColor="#fff" border="none"
							:suffixIcon="data.processDetails.ifComplete!=='Y'? 'arrow-right': ''"
							v-model="data.processDetails.operator"></u--input>
					</view>
				</view>
				<view class="loginFormBox" v-if="data.importantPartslist.length"
					v-for="(item,index) in data.importantPartslist" :key="index">
					<view class="name">关重件：{{item.name}}</view>
					<view class="" v-if="data.processDetails.ifComplete!=='Y'">
						<u-upload :fileList="item.keyfiles" @afterRead="afterRead" :name='`${item.id}`'
							@delete="deletePic" multiple :previewFullImage="true"></u-upload>
					</view>
					<view class="display" v-else>
						<!-- 		<u--image class="upic" v-for="(u,idx) in item.keyfiles" :key="idx" :showLoading="true" :src="u.url"
							width="80px" height="80px"></u--image> -->
						<u-album :urls="item.keyfiles" keyName="url"></u-album>
					</view>
				</view>
				<view class="btns" v-if="data.processDetails.ifComplete!=='Y'">
					<u-button type="primary" :throttleTime="1000" color="#74C3EA" shape="circle" @click="submit" :loading="data.loading"
						:loadingText="data.loadingText">提交</u-button>
				</view>
			</block>
			<mescroll-empty v-else></mescroll-empty>
			<ba-tree-picker ref="treePicker" :multiple='true' @select-change="selectChange" title="选择操作人"
				:defaultValue="data.defaultValue" :localdata="data.listData" valueKey="userId" textKey="nickName"
				childrenKey="children" />
		</view>
	</view>

</template>
<script lang="ts" setup>
	import { processcomplete, getRoleUserList, keyimportantlistnotpage } from '@/api/planList/planList.js'
	import { reactive, ref } from "vue";
	import { onLoad, onUnload } from "@dcloudio/uni-app";
	import base from "@/common/baseUrl.js";
	const base_url = base.uploadImgUrl
	const data : any = reactive({
		loading: false,
		loadingText: '加载中',
		activeStation: null,
		importantPartslist: [],
		keyfiles: [],
		processDetails: null,
		listData: [],
		filterList: [],
		defaultValue: null,
		titleStyle: {
			color: '#fff',
			fontSize: '34rpx',
			fontWeight: '600'
		},
		emptyOption:{
			icon: "/static/empty.png", // 图标路径
			tip: '~ 暂无相关数据 ~', // 提示
		}
	});

	onLoad(() => {
		try {
			uni.$on('processDetails', (e) => {
				data.processDetails = e || {};
				const activeStation = uni.getStorageSync('activeStation');
				data.activeStation = activeStation
				const userInfo = uni.getStorageSync('userInfo')
				if (data.processDetails.ifComplete !== 'Y') {
					data.processDetails.operator = userInfo.nickName
				}
				data.defaultValue = userInfo.userId
				getkeyimportantlistnotpage()
			})
			getRoleUserList({ roleNames: '生产' }).then(res => {
				data.listData = data.filterList = res.rows
			})
		} catch (error) {
			console.log(error,'2222222222')
			//TODO handle the exception
		}
	});
	onUnload(() => {
		uni.$off('processDetails')
	})
	const treePicker = ref()
	const openTree = () => {
		if (data.processDetails.ifComplete !== 'Y') {
			treePicker.value._show()
		}
	}
	const selectChange = (ids, name, list) => {
		// data.processDetails.operator = name
		var arr = []
		list.forEach(item => { arr.push(item.name) })
		data.processDetails.operator = arr.join()
	}

	//获取关重件
	const getkeyimportantlistnotpage = async () => {
		try {
			const res = await keyimportantlistnotpage({ planEqmId: data.processDetails.planEqmId, processId: data.processDetails.processId })
			data.importantPartslist = res.data;
			data.importantPartslist.map(item => {
				let keyfiles = []
				if (item.files && item.files.length) {
					item.files.map(i => {
						const keyfilesObj = {
							fileId: i.id,
							keyId: item.id,
							url: i.uri
						}
						keyfiles.push(keyfilesObj)
					})

				}
				item.keyfiles = keyfiles

			})
		} catch (e) {
			//TODO handle the exception
		}
	}
	//登录
	const submit = async () => {
		try {

			if (!data.processDetails.operator) {
				return uni.showToast({
					title: '选择操作人',
					icon: 'error'
				})
			}
			uni.showModal({
				title: '提示',
				content: '确认完工吗？',
				success: async (res) => {
					if (res.confirm) {
						let params = {
							id: data.processDetails.id
						}
						let keyfiles = []
						data.importantPartslist.map(i => {
							keyfiles = keyfiles.concat(JSON.parse(JSON.stringify(i.keyfiles)))
						})
						keyfiles.map(k => {
							delete k.url
						})
						params.keyfiles = keyfiles;
						params.operator = data.processDetails.operator
						const res = await processcomplete(params)
						if (res.status == 200) {
							uni.navigateBack({
								success: () => {
									uni.$emit('isRefresh', data.processDetails.id)
								}
							});
						}
					}
				}
			});


		} catch (e) {
			//TODO handle the exception
		}
	};
	const afterRead = (e) => {
		try {
			const keyId = e.name;
			let files = e.file;
			if (files.length) {
				files.map(async (item) => {
					uni.uploadFile({
						url: base_url, //接口
						filePath: item.thumb,
						name: 'file',
						header: {
							Authorization: uni.getStorageSync("access_token"),
						},
						file: item,
						formData: {
							id: data.processDetails.id
						},
						success: async res => {
							let resData = JSON.parse(res.data);
							if (resData.status == 200 && resData.data.uri) {
								data.importantPartslist.map((i) => {
									if (i.id == keyId) {
										i.keyfiles.push({
											fileId: resData.data.id,
											keyId: keyId,
											url: resData.data.uri
										})
									}
								})
							}
							//针对拍照上传成功保存图片到本地
							let URL = item.url.startsWith('file://')
							if (!URL) {
								uni.saveImageToPhotosAlbum({
									filePath: item.url
								})
							}
						}
					})
				})
			}

		} catch (e) {
			//TODO handle the exception
		}
	}
	const deletePic = (e) => {
		uni.showModal({
			title: '提示',
			content: '确认要删除该条数据吗？',
			success: function (res) {
				if (res.confirm) {
					const index = e.index;
					const keyId = e.name;
					data.importantPartslist.map(item => {
						if (item.id == keyId) {
							item.keyfiles.splice(index, 1)
						}
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});


	}
</script>
<style lang="scss" scoped>
	.activeStation {
		margin-bottom: 45rpx;
	}

	.name {
		font-size: 36rpx;
	}

	.u-grid-item {
		margin-bottom: 20rpx;
		align-items: flex-start;
	}

	.btns {
		margin-top: 40rpx;
	}

	.loginFormBox {
		margin-bottom: 20rpx;

		.name {
			margin-bottom: 20rpx;
		}
	}

	.display {
		display: flex;
		flex-wrap: wrap;

		.upic {
			margin-right: 20rpx;
			margin-bottom: 20rpx;
		}
	}
</style>